<template>
  <layer :layer="layer" @confirm="submit" ref="layerDom" @close="cancel">
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      style="margin-right: 30px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nickName" style="width: 100%">
            <el-input
              v-model="form.nickName"
              placeholder="请输入用户昵称"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-cascader
              ref="cascader"
              :show-all-levels="false"
              :options="deptRole.depts"
              @change="changeCascader"
              :props="{
                checkStrictly: true,
                expandTrigger: 'hover',
                label: 'deptName',
                value: 'id',
              }"
              v-model="form.deptId"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 手机号码+邮箱 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input
              placeholder="请输入手机号码"
              v-model="form.phoneNumber"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              placeholder="请输入邮箱"
              v-model="form.email"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 用户账号、密码 -->
      <el-row v-if="!layer.row">
        <el-col :span="12">
          <el-form-item label="用户账号" prop="username">
            <el-input
              placeholder="请输入用户名称"
              v-model="form.username"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="请输入用户密码"
              type="password"
              v-model="form.password"
              show-password
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 用户性别、状态 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio
                v-for="(value, key, index) in sexObj"
                :key="index"
                :label="key"
                >{{ value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="(value, key, index) in statusArr"
                :key="index"
                :label="key"
                >{{ value }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 岗位、角色 -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-select v-model="form.postIds" multiple clearable>
              <el-option
                v-for="item in deptRole.posts"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色">
            <el-select v-model="form.roleIds" multiple clearable>
              <el-option
                v-for="item in deptRole.roles"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input type="textarea" placeholder="请输入备注"></el-input>
      </el-form-item>
    </el-form>
  </layer>
</template>
<script>
import { defineComponent, ref, reactive } from "vue";
import layer from "_c/layer/index.vue";
import { ElMessage } from "element-plus";
import { queryDict } from "@/api/dictValue.js";
import { addUser, editUser } from "@/api/user.js";
import { getPub } from "@/api/rsa.js";
import { encode } from "@/utils/system/rsa.js";
export default defineComponent({
  components: { layer },
  props: {
    //用于控制对话框
    layer: {
      required: true,
      type: Object,
      default: () => {
        return {
          show: false,
          title: "",
          showButton: true,
        };
      },
    },
    statusArr: {
      type: Object,
      required: true,
      default: () => {
        return {
          0: "正常",
          1: "禁用",
        };
      },
    },
    deptRole: {
      type: Object,
      required: true,
    },
  },
  setup(props, ctx) {
    //定义公钥
    const publicKey = ref("");
    //表单引用
    const ruleForm = ref(null);
    //级联下拉引用
    const cascader = ref({});
    //性别数据字典
    const sexObj = ref({});
    //表单数据
    let form = ref({
      deptId: undefined,
      roleIds: [],
      postIds: [],
      username: undefined,
      nickName: undefined,
      email: undefined,
      phoneNumber: undefined,
      sex: "0",
      avatar: undefined,
      password: undefined,
      status: "0",
      remark: undefined,
    });
    //校验规则
    const rules = {
      nickName: [
        { required: true, message: "请输入用户昵称", trigger: "blur" },
      ],
      deptId: [{ required: false }],
      phoneNumber: [{ required: false }],
      email: [{ required: false }],
      username: [
        { required: true, message: "请输入用户名称", trigger: "biur" },
      ],
      sex: [{ required: false }],
      password: [
        { required: true, message: "请输入用户密码", trigger: "biur" },
      ],
      status: [{ required: true, message: "请选择状态", trigger: "biur" }],
      remark: [{ required: false }],
    };
    const submit = () => {
      if (ruleForm) {
        //规则校验
        ruleForm.value.validate((valid) => {
          if (valid) {
            let params = form.value;
            if (props.layer.row) {
              updateForm(params);
            } else {
              addForm(params);
            }
          } else {
            return false;
          }
        });
      }
    };
    //更新数据
    const updateForm = async (obj) => {
      if (obj) {
        delete obj.username;
        delete obj.password;
        const data = await editUser(obj);
        if (data.success) {
          props.layer.show = false;
          cancel();
          ctx.emit("getTableData");
          ElMessage.success("操作成功！");
        }
      }
    };
    //新增数据
    const addForm = async (obj) => {
      if (obj) {
        let pwd = obj.password;
        let pwdStr = encode(pwd, publicKey.value);
        console.log(pwdStr);
        obj.password = pwdStr;
        const data = await addUser(obj);
        if (data.success) {
          props.layer.show = false;
          cancel();
          ctx.emit("getTableData");
          ElMessage.success("操作成功！");
        }
      }
    };
    //关闭对话框
    const cancel = () => {
      ruleForm.value.resetFields();
    };
    //挂载
    const init = () => {
      if (props.layer.row) {
        form.value = JSON.parse(JSON.stringify(props.layer.row));
      }
    };
    init();
    //获取公钥
    const getPublickKey = async () => {
      const { data, success } = await getPub();
      if (success) {
        publicKey.value = data;
      }
    };
    getPublickKey();
    //查询用户性别字典
    const querySex = async () => {
      const { data, success } = await queryDict("user_sex");
      if (success) {
        sexObj.value = data;
      }
    };
    querySex();
    //级联选择，取其一
    const changeCascader = (arr) => {
      if (arr) {
        form.value.deptId = arr[arr.length - 1];
      }
      cascader.value.togglePopperVisible();
    };

    return {
      ruleForm,
      cascader,
      sexObj,
      form,
      rules,
      submit,
      cancel,
      changeCascader,
    };
  },
});
</script>
<style lang="scss" scoped></style>
